import os
from common import get_logger, browser, safe_filename, session
import subprocess

# 从config模块导入抖音视频保存的目录常量
from config import DOUYIN_SAVE_DIR

logger = get_logger(__name__)


def is_logged_in_js(tab):
    js_source = """
        if(document.querySelector("span.semi-avatar img")){
            return true;
        }
        return false;
    """
    try:
        return tab.run_js(js_source)
    except Exception as e:
        logger.error(f"检查登录时出现错误:{e}")
        tab.wait(2)  # time.sleep(2)


# 定义爬取抖音热门视频的函数，参数为关键词
def crawl_douyin_videos(keyword):
    logger.info("开始爬取抖音热门视频")

    # 构建抖音搜索的页面的URL地址
    url = f"https://www.douyin.com/root/search/{keyword}?type=video"
    # 如果保存视频的目录不存在，则创建该目录
    if not os.path.exists(DOUYIN_SAVE_DIR):
        os.makedirs(DOUYIN_SAVE_DIR)
    # 打开新的标签页，并且访问抖音搜索地址
    tab = browser.new_tab(url)
    # 启动监听，捕获视频的真实地址
    tab.listen.start("/video/tos")
    while True:
        try:
            if is_logged_in_js(tab):
                break
            logger.info(f"等待登录中，请扫码登录抖音账号")
            tab.wait(2)
        except Exception as e:
            logger.error(f"等待登录异常:{e}")
            tab.wait(2)  # time.sleep(2)
    logger.info(f"检测到已经登录，继续执行")
    # 获取所有的视频卡片元素
    video_cards = tab.eles(".search-result-card")
    logger.info(f"共找到{len(video_cards)}个视频卡片")
    # 只处理第一个卡片
    video_cards = video_cards[:1]
    logger.info(f"先处理{len(video_cards)}个视频卡片")

    # 初始化视频文件的列表
    video_files = []
    # 遍历每个卡片 idx为序号 card为卡片的元素
    for idx, card in enumerate(video_cards, 1):
        try:
            # 鼠标悬停到卡片
            card.hover()
            # 获取视频标题
            title = card.ele(".VDYK8Xd7").text
            # 生成安全的文件名
            filename = safe_filename(idx, title, ".mp4")
            logger.info(f"视频文件名:{filename}")
            # 等待监听获取真实的视频地址
            real_video_url = tab.listen.wait().url
            # real_video_url = "https://v26-web.douyinvod.com/571ce4e9a752e0b8346034e49b960cc1/6861584d/video/tos/cn/tos-cn-ve-15/oUUfzWgM2i2gDDpoACQAECINfXAtiBADYBz9Si/?a=6383&ch=11&cr=3&dr=0&lr=all&cd=0%7C0%7C0%7C3&cv=1&br=1255&bt=1255&cs=0&ds=6&ft=4TMWc6Dnppft2zLd.sd.C_bAja-CIn1VHBGc6B3L2r.qSYpHDDHL-A_6fROIRusZ.&mime_type=video_mp4&qs=1&rc=NDhoZWU8ODw0ZzU1ZzQ7NEBpM3JzdG05cmR4NDMzNGkzM0BhLy8tMV9hNmIxYy4uNWBfYSMuYGIuMmRjazJhLS1kLTBzcw%3D%3D&btag=80000e00010000&cquery=100K_100o_101n_100B_100H&dy_q=1751199236&feature_id=46a7bb47b4fd1280f3d3825bf2b29388&l=202506292013553AB481A680491340B1E8"
            logger.info(f"真实的视频为:{idx} {real_video_url}")
            # 发送GET请求视频地址获取视频数据
            video_data = session.get(
                real_video_url,
                headers={
                    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36",
                    "referer": "https://www.douyin.com/",
                },
                timeout=10,
            )
            # 拼接保存的文件的路径
            file_path = os.path.join(
                os.path.dirname(os.path.abspath(__file__)), DOUYIN_SAVE_DIR, filename
            )
            logger.info(f"保存的路径为:{file_path}")
            # 以二进制的格式保存视频文件
            with open(file_path, "wb") as file:
                file.write(video_data.content)

            video_files.append({
                "title": title,
                "file_path": file_path
            })
                
        except Exception as e:
            logger.error(f"处理视频失败:{e}")
            continue
        finally:
            tab.wait(2)
    return video_files


def extract_audio(video_path):
    # 1.获得转换后的mp3的文件名
    base_name = os.path.basename(video_path)
    filename = os.path.splitext(base_name)[0]
    base_dir = os.path.dirname(video_path)
    mp3_path = os.path.join(base_dir, f"{filename}.mp3")
    # 构建命令行参数列表
    cmd = [
        "ffmpeg",
        "-y",  # 覆盖输出文件
        "-i",  # 输入文件
        video_path,
        "-vn",  # 不处理视频流
        "-acodec",  # 指定音频编码器
        "libmp3lame",
        "-ar",  # 指定音频采样率
        "44100",
        "-ac",  # 指定音频声道数
        "2",
        "-ab",  # 指定音频比特率
        "192k",
        mp3_path,  # 输出文件路径
    ]
    try:
        subprocess.run(cmd, check=True)
    except Exception as e:
        logger.error(f"音频提取失败:{e}")
    return mp3_path

